// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-2ga6780q302b7f4a'
}) // 使用当前云环境
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  
  try {
    // 验证管理员身份
    const result = await cloud.callFunction({
      name: 'checkAdminAuth',
      data: {
        adminId: event.adminId || '',
        token: event.token || ''
      }
    })
    
    const { code, data } = result.result
    
    if (code !== 0 || !data) {
      return {
        code: 401,
        data: null,
        message: '未授权访问'
      }
    }
    
    // 参数验证
    if (!event.equipmentId || !event.equipment) {
      return {
        code: -1,
        data: null,
        message: '参数不完整'
      }
    }
    
    // 构建更新数据
    const updateData = {
      name: event.equipment.name,
      description: event.equipment.description || '',
      category: event.equipment.category || '其他',
      imageUrl: event.equipment.imageUrl || '',
      creditRequired: event.equipment.creditRequired || 60,
      status: event.equipment.status === 1 ? '可借用' : '不可借用',
      updateTime: db.serverDate()
    }
    
    // 检查集合是否存在，不存在则创建
    try {
      const collections = await db.listCollections().get();
      const collectionList = collections.data.map(col => col.name);
      
      if (!collectionList.includes('equipment')) {
        await db.createCollection('equipment');
        console.log('成功创建equipment集合');
        // 如果集合刚刚被创建，则直接返回成功信息，因为没有数据可以更新
        return {
          code: 0,
          data: null,
          message: '集合刚刚创建，请先添加装备'
        }
      }
    } catch (error) {
      console.error('检查或创建集合失败:', error);
    }
    
    // 更新装备
    await db.collection('equipment').doc(event.equipmentId).update({
      data: updateData
    })
    
    return {
      code: 0,
      data: null,
      message: '更新装备成功'
    }
  } catch (err) {
    return {
      code: 500,
      data: null,
      message: '更新装备失败: ' + err.message
    }
  }
} 